<template>
  <div class="HCFormFied field-box">
    <div class="attachment-box field-item upload-button">
      <div class="upload-button__right">
          <el-button
            style="margin-left: 10px"
            type="primary"
            icon="el-icon-plus"
            class="applay-sign"
            @click="handleOpenSignDialog"
            v-if="!signImage"
            >{{ btnTitle }}</el-button
          >

        <div class="applay-sign--box" v-else>
          <i 
            v-if="showDelete"
            class="el-icon-circle-close icon-sign-delete"
            @click="handleRemoveSign(signImage, title)"
          ></i>
          <el-image
            class="applay-sign__image"
            :src="signImage.url"
            :preview-src-list="[signImage.url]"
          >
          </el-image>
        </div>
      </div>
    </div>
    <SignatureDialog
      title="申请人签名"
      :visible.sync="dialogVisible"
      :confirm="onSignatureConfirm"
    />
    <!-- 签名协议弹窗 -->
    <AgreeDialog ref="AgreeDialog" />
  </div>
</template>
<script>
import {
  openUpload,
  getOpenList,
  delAttachment,
  getOpenDownloadUrl,
} from "../../api/common/attachment";
import SignatureDialog from "../SignatureDialog.vue";
import AgreeDialog from "./AgreeDialog.vue";
import { handleError } from "hc-core/utils";
export default {
  name: "SignaturePad",
  props: {
    //上传按钮标题
    title: {
      type: String,
      default: "",
    },
    //文件关联数据unid
    relationUnid: {
      type: String,
      default: "",
    },
    //模块名
    moduleName: {
      type: String,
      default: "",
    },
    //表单类型
    formType: {
      type: String,
      default: "",
    },
    //类型
    type: {
      type: String,
      default: "",
    },
    //状态
    disabled: {
      type: Boolean,
      default: false,
    },
    //是否必填
    isRequire: {
      type: Boolean,
      default: false,
    },
     //协议
    agreement: {
      type: Boolean,
      default: false,
    },
    //协议模块名称
    agreeModuleName:{
      type: String,
      default: "",
    },
    //表单类型
    agreeFormType: {
      type: String,
      default: "",
    },
     //是否显示删除
    showDelete: {
      type: Boolean,
      default: false,
    }
  },
  components: {
    SignatureDialog,
    AgreeDialog
  },
  data() {
    return {
      uploading: false, //显示loading
      fileList: [], //文件列表
      //是否显示弹窗
      dialogVisible: false,
      //签名url
      signImage: null,
    };
  },
  computed: {
    btnTitle() {
      if (this.title) {
        return this.title;
      }
      return "签名";
    },
  },
  created() 
  {
    // 查询文件列表
    this.getSignAttachList();
  },
  methods: {
    //打开弹窗
    handleOpenSignDialog: handleError(async function(){
      if(this.agreement){
        await this.$refs.AgreeDialog.requestAgree(this.agreeModuleName,this.agreeFormType);  
      }
      this.dialogVisible = true;
    })
    ,
      /**
     * 将Base64字符串转换为PNG文件
     * @param {string} base64Str - Base64编码的图片字符串
     */
    base64ToImage(base64Str) {
      // 将Base64字符串转换为二进制数据
      const byteCharacters = atob(base64Str.split(",")[1]); // 去掉 data:image/png;base64, 部分
      const byteArrays = [];

      for (let offset = 0; offset < byteCharacters.length; offset++) {
        const byte = byteCharacters.charCodeAt(offset);
        byteArrays.push(byte);
      }

      // 创建一个Blob对象，指定MIME类型为image/png
      const byteArray = new Uint8Array(byteArrays);
      const blob = new Blob([byteArray], { type: "image/png" });
      return blob;
    },
    //签名确认
    onSignatureConfirm(P_Base64){
      return new Promise((resolve,reject) => {
      const blob = this.base64ToImage(P_Base64);
      const formData = new FormData();
      formData.append("file", blob, "image.png");
      formData.append("relationUnid", this.relationUnid);
      formData.append("moduleName", this.moduleName);
      formData.append("type", this.type);
      openUpload(formData,(progress) => {
        console.log("上传进度",progress);
      })
      .then(res =>
        {
          this.$message.success("上传成功");
           //  设置图片
          const item = res.result;
          item.uid = item.unid;
          item.status = "done";
          item.url = getOpenDownloadUrl(item.unid);
          item.name = item.fileName;
          item.xh = item.xh + 1;
          this.signImage = item;
          resolve();
        })
        .catch(P_Error =>
        {
          console.error("[接口异常]", P_Error);
          this.$message.error("上传失败");
          reject();
        });
      })
    },
    // 查询文件列表
    getSignAttachList() {
      if (
        this.relationUnid === "" ||
        typeof this.relationUnid === "undefined" ||
        this.moduleName === ""
      ) {
        return;
      }
      const params = {
        relationUnid: this.relationUnid,
        moduleName: this.moduleName,
        type: this.type,
        pageNum: 1,
        pageSize: 100,
      };
      getOpenList(params)
        .then((res) => {
          if (res.code === 200) {
            res.result.data.map((item, index) => {
              item.url = getOpenDownloadUrl(item.unid);
              this.signImage = item;
            });
          } else if (res.message.includes("allowed extension")) {
            this.$message.error("文件格式不受支持，请更换");
          } else {
            this.$message.error("上传失败,请重试！");
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //文件删除
    handleRemoveSign(file, btnTitle) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        delAttachment({ unids: file.unid })
          .then((res) => {
            this.$message.success(`${btnTitle}删除成功`);
            this.signImage = null;
          })
          .catch((err) => {
            console.log(err);
          });
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.upload-button {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-end;
}
.attachment-box {
  width: 100%;
  height: 100%;
  padding-left: 10px;
  display: flex;
  align-items: flex-end;

  .el-icon-plus {
    font-size: 16px;
    margin: 10px auto;
    border: 2px solid #333;
    padding: 4px;
    border-radius: 4px;
  }
}

::v-deep .el-icon-caret-right {
  width: 0;
  padding: 0;
}

.upload-button__right {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  .applay-sign--box {
    position: relative;
    .icon-sign-delete {
      position: absolute;
      right: -5px;
      top: -5px;
      z-index: 10;
      color: red;
      display: none;
    }
  }

  .applay-sign--box:hover {
    .icon-sign-delete {
      display: flex;
    }
  }
  .applay-sign__image {
    height: 80px;
    width: auto;
  }
}
</style>
